import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:talk/pages/device/x_device_router.dart';

import '../../api/ShareApi.dart';
import '../../api/dio/DioClient.dart';
import '../../commponets/ItemView.dart';
import '../../home/AppLocale.dart';
import '../../routers/fluro_navigator.dart';
import '../../tools/widgets/my_app_bar.dart';
import '../../utils/toast_utils.dart';
import '../my/model/UserModel.dart'; // 引入UserModel


class DeviceSharePage extends StatefulWidget {
  const DeviceSharePage({
    super.key,
    this.deviceId,
    this.userId,
  });

  final int? deviceId;
  final int? userId;

  @override
  State<DeviceSharePage> createState() => _DeviceSharePageState();
}


class _DeviceSharePageState extends State<DeviceSharePage> {
  final ShareApi _shareApi = ShareApi();
  late int _deviceId;
  late int _userId;
  // 存储后端返回的原始分享列表数据
  List<Map<String, dynamic>> _shareList = [];
  // 加载状态标识
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _deviceId = widget.deviceId!;
    _userId = widget.userId!;

    _fetchData();
  }


  Future<void> _fetchData() async {
    print("ddddddddddddd");
    try {
      setState(() => _isLoading = true);

      final response = await _shareApi.getShareList(_deviceId);
      if (response.code == 200 && response.data != null) {
        setState(() {
          _shareList = (response.data as List).cast<Map<String, dynamic>>();
        });
      } else {
        Toast.show(response.getMsg ?? "获取数据失败");
      }
    } catch (e) {
      Toast.show("获取数据异常: ${e.toString()}");
    } finally {
      setState(() => _isLoading = false);
    }
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: AppLocale.text('d_fenxiangshebei'),
        backgroundColor: Colors.transparent,
        dropdownWidth: 140,
        dropdownBackgroundColor: Colors.white,
        dropdownBorderRadius: 20,
      ),
      body: Container(
        child: Column(
          children: [
            const SizedBox(height: 20),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 27.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    AppLocale.text('d_yifenxinagyonghu'),
                    style: TextStyle(fontSize: 13.0, color: Colors.black),
                  ),
                  Material(
                    // 移除Material默认背景，避免影响原有UI
                    color: Colors.transparent,
                    child: InkWell(
                      // 点击水波纹颜色（可选，默认主题色）
                      splashColor: Colors.grey[200],
                      // 点击高亮颜色（可选）
                      highlightColor: Colors.grey[100],
                      // 点击触发的方法
                      onTap: (){

                        NavigatorUtils.pushResult(
                          context,
                            '${XDeviceRouter.deviceShareAddPage}?deviceId=$_deviceId&userId=$_userId', (result) {
                          _fetchData();
                        },
                        );

                      },
                      child: Row(
                        children: [
                          Text(
                            AppLocale.text('d_add'),
                            style: TextStyle(fontSize: 13.0, color: Colors.black38),
                          ),
                          SizedBox(width: 5),
                          Icon(
                            Icons.arrow_forward_ios,
                            color: Colors.grey,
                            size: 14,
                          ),
                        ],
                      ),
                    ),
                  )
                ],
              ),
            ),
            const SizedBox(height: 17),
            // 动态列表区域
            _isLoading
                ? const Center(child: CircularProgressIndicator())
                : _shareList.isEmpty
                ? Center(
              child: Text(AppLocale.text('d_wuadd'), style: TextStyle(color: Colors.grey)),
            )
                : Expanded(
              child: ListView.builder(
                padding: const EdgeInsets.symmetric(horizontal: 15),
                itemCount: _shareList.length,
                itemBuilder: (context, index) {
                  // 获取当前项数据
                  final shareItem = _shareList[index];
                  // 解析用户信息（处理null情况）
                  final userMap = shareItem['toUser'] as Map<String, dynamic>?;
                  final user = userMap != null ? UserModel.fromJson(userMap) : null;
                  // 直接获取头像和昵称（带默认值）
                  final avatarUrl = '${DioClient.baseUrl}${user!.avatar}' ?? 'http://43.139.39.5:82/pho/face/default.jpg';
                  final userName = user.userName ?? AppLocale.text('d_weizhiyonghu');
                  final phone = user.phonenumber ?? '';

                  // 直接返回ItemView
                  return Padding(
                    padding: const EdgeInsets.symmetric(vertical: 4.0),
                    child: ItemView(
                      width: 400,
                      height: 65,
                      leftPadding: 10,
                      rightPadding: 20,
                      leftWidget: Row(
                        children: [
                          const SizedBox(width: 10),
                          CircleAvatar(
                            radius: 18,
                            backgroundColor: Colors.grey[200],
                            child: ClipOval(
                              child: Image.network(
                                avatarUrl,
                                width: 45,
                                height: 45,
                                fit: BoxFit.cover,
                                errorBuilder: (context, error, stackTrace) =>
                                    Image.network(
                                      'http://43.139.39.5:82/pho/face/default.jpg',
                                      width: 45,
                                      height: 45,
                                      fit: BoxFit.cover,
                                    ),
                              ),
                            ),
                          ),
                          const SizedBox(width: 10),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text(
                                userName,
                                style: const TextStyle(
                                  fontSize: 15,
                                  // fontWeight: FontWeight.w500,
                                ),
                              ),
                              const SizedBox(height: 4),
                              Text(
                                phone,
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Colors.grey[600],
                                ),
                              ),
                              const SizedBox(height: 3),
                            ],
                          ),

                        ],
                      ),
                      borderRadius: 8,
                      onTap: () {
                        int shareId = shareItem['shareId'];
                        final toId = shareItem['toId'];

                        NavigatorUtils.pushResult(
                          context,
                          '${XDeviceRouter.deviceSpecificsPage}?deviceId=$_deviceId'
                              '&shareId=$shareId&toId=$toId', (result) {
                          _fetchData();},
                        );

                      },
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
